<template>
  <view class="level-select" :style="{ paddingTop: customBarHeight + 'px' }">
    <view class="navbar">
      <view class="navbar-left">
        <button class="back-btn" @tap="goBack">
          <text class="back-icon">←</text>
        </button>
      </view>
      <view class="navbar-center">
        <text class="navbar-title">选择关卡</text>
      </view>
      <view class="navbar-right"></view>
    </view>

    <scroll-view scroll-y>
      <view class="level-grid">
        <view class="level-item" v-for="level in levels" :key="level.L_id" @tap="selectLevel(level.L_id)"
          :class="{ 'completed': isLevelCompleted(level.L_id) }">
          <text class="level-number">{{ level.L_id }}</text>
          <text class="level-title">{{ level.L_Title }}</text>
          <text class="level-author">{{ level.L_Author }}</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { ref, onMounted } from 'vue'
import Taro from '@tarojs/taro'
// import levelsData from '@/assets/levels/sokoban100.json'
import levelsData from '../../assets/levels/sokoban100.js'
import './level-select.scss'

// 跨端存储读取
function getStorageSync(key) {
  if (Taro.getStorageSync && typeof Taro.getStorageSync === 'function') {
    return Taro.getStorageSync(key)
  } else if (typeof window !== 'undefined' && window.localStorage) {
    return window.localStorage.getItem(key)
  }
  return null
}

export default {
  setup() {
    const customBarHeight = ref(0)
    const levels = ref([])
    const completedLevels = ref(new Set())

    onMounted(async () => {
      const systemInfo = Taro.getSystemInfoSync();
      const statusBarHeight = systemInfo.statusBarHeight;
      customBarHeight.value = statusBarHeight + 44; // 44 是导航栏高度
      levels.value = levelsData
      // 获取已完成的关卡
      const completed = getStorageSync('completedLevels') || []
      // 兼容 localStorage 字符串存储
      let completedArr = completed
      if (typeof completed === 'string') {
        try {
          completedArr = JSON.parse(completed)
        } catch (e) {
          completedArr = []
        }
      }
      completedLevels.value = new Set(completedArr)
    })

    const goBack = () => {
      // 尝试返回上一页，如果失败则跳转到首页
      try {
        const pages = Taro.getCurrentPages()
        if (pages.length > 1) {
          Taro.navigateBack()
        } else {
          // 如果导航栈中只有当前页面，则跳转到首页
          Taro.redirectTo({
            url: '/pages/index/index'
          })
        }
      } catch (error) {
        // 如果navigateBack失败，直接跳转到首页
        Taro.redirectTo({
          url: '/pages/index/index'
        })
      }
    }

    const selectLevel = (levelId) => {
      Taro.navigateTo({
        url: `/pages/game/game?level=${levelId}`
      })
    }

    const isLevelCompleted = (levelId) => {
      return completedLevels.value.has(levelId)
    }

    return {
      levels,
      goBack,
      selectLevel,
      isLevelCompleted,
      customBarHeight
    }
  }
}
</script>